package com.xc.disk.utils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.esotericsoftware.reflectasm.MethodAccess;
import com.xc.disk.bean.QueryBean;
import com.xc.disk.info.TokenInfo;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>项目名称: Stars</p>
 * <p>描述: Service层封装数据工具类</p>
 * <P>创建人: 小程</p>
 * <P>创建人邮箱: 779943476@qq.com</p>
 * <p>创建时间: 2019/7/1</p>
 *
 * @version v1.0
 */
public class ServiceUtils {
    /**
     * <p>功能描述: 封装查询条件</p>
     * <p>更新人: 小程</p>
     * <p>更新描述: 添加方法</p>
     * <p>更新人邮箱: 779943476@qq.com</p>
     * <p>更新时间: 2019/7/1</p>
     *
     * @param queryBean 查询排序条件
     * @param t         用户查询实体
     * @return 返回QueryWrapper查询对象
     */
    public static <T> QueryWrapper<T> queryData(QueryBean queryBean, T t, TokenInfo token) {
        QueryWrapper<T> queryWrapper = new QueryWrapper<T>();
        boolean bool = false;
        if ("ASC".toUpperCase().equals(queryBean.getRule().toUpperCase())) {
            bool = true;
        }
        if (queryBean.getSortFields() == null) {
            queryWrapper.orderBy(true, bool, "id");
        } else {
            queryWrapper.orderBy(true, bool, queryBean.getSortFields());
        }
        if (queryBean.getLikeFields() != null) {
            MethodAccess methodAccess = MethodAccess.get(t.getClass());
            for (String likeField : queryBean.getLikeFields()) {
                queryWrapper.like(likeField, methodAccess.invoke(t, likeField));
            }
        }
        queryWrapper.setEntity(t);
        List<Object> ids = new ArrayList<>();
        if (token != null && token.getUserIds() != null && token.getUserIds().size() != 0) {
            ids.addAll(token.getUserIds());
        }
        if (token != null && token.getUserId() != null) {
            ids.add(token.getUserId());
        }
        queryWrapper.in("user_id", ids);
        return queryWrapper;
    }
}
